//
//  XLUserCenterHeaderView.m
//  industry
//
//  Created by xl on 2020/11/24.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLUserCenterHeaderView.h"
#import "XLUserDefaults.h"
#import "YQUserCenterHeaderViewModel.h"

@interface XLUserCenterHeaderView ()

@property (nonatomic, strong) XLImageView *bgIG;
@property (nonatomic, strong) XLView *avaterbgView;
@property (nonatomic, strong) XLImageView *avaterIG;
@property (nonatomic, strong) XLLabel *titleLB;
@property (nonatomic, strong) XLLabel *authorLB;
@property (nonatomic, strong) XLLabel *accountLB;

@property (nonatomic, strong) YQUserCenterHeaderViewModel *viewModel;
@end

@implementation XLUserCenterHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteBgColor];
        self.viewModel = [YQUserCenterHeaderViewModel new];
        [self addSubview:self.bgIG];
        self.bgIG.userInteractionEnabled = YES;
        [_bgIG addSubview:self.avaterbgView];
        [_avaterbgView addSubview:self.avaterIG];
        [_bgIG addSubview:self.titleLB];
        [_bgIG addSubview:self.authorLB];
        [_bgIG addSubview:self.accountLB];
        
        [self makeConstraints];
        
        self.userInteractionEnabled = YES;
        
        WEAKSELF
        [self.avaterIG setTouchBegan:^{
            
            [weakSelf.viewModel setAvatarImage];
        }];
        
        NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
        [self.viewModel addObserver:self forKeyPath:@"avatarIm" options:options context:nil];
        
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.avaterIG setImage: self.viewModel.avatarIm];
    });
   
    NSLog(@"监听到%@的%@属性值改变了 - %@ - %@", object, keyPath, change, context);
}

#pragma mark - Private
- (void)makeConstraints {
    [_bgIG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self);
        make.height.mas_equalTo(SCREEN_WIDTH * 262/375.0);
    }];
    int topx = (STATUSBAR_HEIGHT == 47) ? -10 : 0 ;
    int top = ((SCREEN_WIDTH * 262/375.0) - topx - 179)/2;
    
    [_avaterbgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgIG);
        make.top.equalTo(self.bgIG).offset(top + 5);
        make.size.mas_equalTo(CGSizeMake(82, 82));
    }];
    
    [_avaterIG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.avaterbgView);
        make.size.mas_equalTo(CGSizeMake(72, 72));
    }];
    
    [_titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avaterbgView.mas_bottom).offset(9);
        make.centerX.equalTo(self.bgIG);
    }];
    [_titleLB sizeToFit];
    
    [_authorLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLB.mas_bottom).offset(10);
        make.centerX.equalTo(self.bgIG);
    }];
    [_authorLB sizeToFit];
    
    [_accountLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.authorLB.mas_bottom).offset(10);
        make.centerX.equalTo(self.bgIG);
    }];
    [_accountLB sizeToFit];
}

- (void)refreshTableView:(XLUserInfo *)info {
    _titleLB.text = [NSString stringWithFormat:@"欢迎您，%@", info.employeeName];
    _authorLB.text = [NSString stringWithFormat:@"认证户名：%@", info.lastLoginCompanyName];
    NSString *account = [XLUserDefaults getLastLoginPhone];
    if (!ISEmptyString(account) && account.length == 11) {
        account = [account stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    _accountLB.text = [NSString stringWithFormat:@"登录账号：%@", account];
    
    /*
     直接拿URL判断是否能取到
     把之前是存储imagedata找到，并删除
     存储新的的路径，和iamgedata
     */
    
//    [XLUserDefaults ]
    if(info.avatar){
        NSData * data = [XLStandardUserDefaults dataForKey:info.avatar];
        UIImage * iamge = [UIImage imageWithData:data];
        if (iamge) {
            [self.avaterIG setImage:iamge];
        }else{
            [self.viewModel getAvatarImageUrlWithPaht:info.avatar success:^(NSString * _Nonnull url) {
                if (!url) return;
                [self.avaterIG sd_setImageWithURL:XLWebIMAGEURL(url) placeholderImage:XLIMAGE(@"avaterbg") completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    if ([XLUserDefaults getAvaterPath]) {
                        [XLStandardUserDefaults setObject:nil forKey:[XLUserDefaults getAvaterPath]];
                        
                    }
                    [XLUserDefaults saveAvaterPath:info.avatar];
                    NSData * data  = UIImageJPEGRepresentation(image, 1);
                    [XLStandardUserDefaults setObject:data forKey:info.avatar];
                }];
                
            }];
        }
    }else{
        self.avaterIG.image = XLIMAGE(@"avaterbg");
    }
    
}

#pragma mark - setter/getter
- (XLImageView *)bgIG {
    if (!_bgIG) {
        _bgIG = [XLImageView new];
        _bgIG.image = XLIMAGE(@"yhbg");
    }
    return _bgIG;
}

- (XLView *)avaterbgView {
    if (!_avaterbgView) {
        _avaterbgView = [XLView new];
        _avaterbgView.backgroundColor = [UIColor colorWithHex:0xffffff alpha:0.6];
        _avaterbgView.layer.cornerRadius = 41;
        _avaterbgView.layer.masksToBounds = YES;
    }
    return _avaterbgView;
}

- (XLImageView *)avaterIG {
    if (!_avaterIG) {
        _avaterIG = [XLImageView new];
        _avaterIG.layer.cornerRadius = 36.0f;
        _avaterIG.image = XLIMAGE(@"avaterbg");
        [_avaterIG setContentMode:UIViewContentModeScaleAspectFill];
        _avaterIG.layer.masksToBounds = YES;
    }
    return _avaterIG;
}

- (XLLabel *)titleLB {
    if (!_titleLB) {
        _titleLB = [XLLabel new];
        _titleLB.font = [UIFont fontOfPingFangSCSemiboldWithSize:20];
        _titleLB.textColor = [UIColor whiteFontColor];
    }
    return _titleLB;
}

- (XLLabel *)authorLB {
    if (!_authorLB) {
        _authorLB = [XLLabel new];
        _authorLB.font = [UIFont fontOfPingFangSCRegularWithSize:12];
        _authorLB.textColor = [UIColor colorWithHex:0xFFFFFF alpha:0.8];
    }
    return _authorLB;
}

- (XLLabel *)accountLB {
    if (!_accountLB) {
        _accountLB = [XLLabel new];
        _accountLB.font = [UIFont fontOfPingFangSCSemiboldWithSize:16];
        _accountLB.textColor = [UIColor whiteFontColor];
    }
    return _accountLB;
}

-(void)dealloc{
    [self.viewModel removeObserver:self forKeyPath:@"avatarIm"];
}

@end
